/**
 * Created with IntelliJ IDEA.
 * User: "Balasubramanian"
 * Date: 8/9/13
 * Time: 12:15 PM
 * To change this template use File | Settings | File Templates.
 */

/*
------------------------------------------------------------------------

Biblioteca represents a e-library management system
It uses Library object internally to represent its collection of books
Biblioteca allows a user to perform the following tasks:
1) View the list of all books
2) Check-out/Borrow a book
3) Check-in/Return a book
4) View membership details

Errors are logged by the java.util.Logger object

--------------------------------------------------------------------------
 */



import java.io.*;
import java.util.*;
import java.util.logging.Logger;



public class Biblioteca {

    static final String BOOK_LIST_FILE="bookList.txt";    // source file containing the list of books
    static final String LOG_FILE="errorLog.log";          // log file name
    private static Library library;                       // Library object
    private static Logger logger;                         // Logger object


    public static void main(String[] args)
    {

        logger=UtilityFunctions.getLogger(LOG_FILE,"errorLog");       // getting the logger object
        library=new Library(BOOK_LIST_FILE,logger);                   // instantiating the Library object

        System.out.println("Welcome to Biblioteca!");                 // Welcome message

        pollUser();

        System.out.println("Thank you! Come again");

        UtilityFunctions.cleanUpLogger(logger);

    }

    // This function polls the user for his options and performs the appropriate service
    private static void pollUser()
    {
        boolean done=false;
        BufferedReader reader=null;
        try
        {
            reader=new BufferedReader(new InputStreamReader(System.in));
        }
        catch(Exception e)
        {
            logger.severe(e.getMessage());
            System.out.println("Sorry, the system has encountered an error. Please try again later.");
            System.exit(1);
        }

        System.out.println("MENU:");
        System.out.println("--------------------------------------------------------------");
        System.out.println("1.Display all books \n2.Reserve book \n3.Return book \n4.Membership details \n5.Exit");
        System.out.println("--------------------------------------------------------------\n");

        do
        {
            int userOption=readOptionFromUser(reader);

            switch(userOption)
            {
                case 1:
                    printAllBooks();
                    break;
                case 2:
                    reserveBook(reader);
                    break;
                case 3:
                    returnBook(reader);
                    break;
                case 4:
                    membershipEnquiry();
                    break;
                case 5:
                    done=true;
                    break;
            }
        }while(!done);

        library.saveToFile() ;
    }

    // This method displays all the books in the library
    private static void printAllBooks()
    {
        System.out.println("List of books in the library:");
        System.out.println("---------------------------");
        System.out.println("Id |  Name  |  Availability");
        System.out.println("---------------------------");
        ArrayList<Book> books=library.getAllBooks();
        for(Book b:books)
        {
            System.out.println(b.getId()+"  | "+b.getName()+" | "+b.getAvailability());
        }
        System.out.println();
    }

    // This method reserves a book for the user
    private static void reserveBook(BufferedReader reader)
    {
       System.out.print("Please enter the id of the book you would like to reserve :");
        try
        {
            String id=reader.readLine();
            if(library.isBookAvailable(id)) // book can be reserved
            {
                library.checkOut(id);
                System.out.println("Thank you! Enjoy the book!\n");
            }
            else   // book has already been reserved by someone else or the library does not have this book
            {
                System.out.println("Sorry, the book is not available yet\n");
            }
        }
        catch(IOException e)
        {
            logger.severe(e.getMessage());
            System.out.println("Sorry, there is some problem with the system. Please try again later");
            System.exit(1);
        }
    }


    // This method is used to return a book, that has been borrowed by the user, to the library
    private static void returnBook(BufferedReader reader)
    {
        System.out.print("Please enter the id of the book to be returned :");
        try
        {
            String id=reader.readLine();
            if(library.hasBook(id) && !library.isBookAvailable(id)) // valid return of a book
            {
                library.checkIn(id);
                System.out.println("The book has been successfully returned! Thank you!\n");
            }
            else  // the book id is either invalid or it has not been borrowed at all!
            {
                System.out.println("Please enter a valid book id!\n");
            }
        }
        catch(IOException e)
        {
            logger.severe(e.getMessage());
            System.out.println("Sorry, there is some problem with the system. Please try again later");
            System.exit(1);
        }
    }

    // Provides details about the member
    private static void membershipEnquiry()
    {
        System.out.println("Please talk to a Librarian. Thank you!\n");
    }

    private static int readOptionFromUser(BufferedReader reader)
    {
        int userOption=0;
        boolean gotValidOption=false;
        do {
            try
            {
                System.out.print("Please enter your option:");
                String input=reader.readLine();
                userOption=Integer.parseInt(input);
                if(userOption<=0 || userOption>5)
                {
                    System.out.println("Please enter a valid option!\n");
                    continue;
                }
                gotValidOption=true;
            }
            catch(NumberFormatException e)
            {
                System.out.println("Please enter a valid option!\n");
                continue;
            }
            catch(IOException e)
            {
                logger.severe(e.getMessage());
                System.out.println("Sorry, the system is not able to process requests. Please try again later");
                System.exit(1);
            }
        }while(!gotValidOption);

        return userOption;
    }
}